<script setup>
import { useChat } from '../composables/useChat'
import { useAuth } from '../composables/useAuth'
import { ref, watch, provide, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router' // 导入 useRouter
import { ArrowLeft, ArrowRight, Plus, Delete, Menu, Promotion } from '@element-plus/icons-vue' // 导入 Promotion 图标
import { ElIcon } from 'element-plus' // 确保导入 ElIcon

const router = useRouter() // 获取 router 实例
const { isAuthenticated, authToken, user, logout, handleUnauthorized } = useAuth();

// 注意：这里不再需要 showLoginModalRef，因为未登录会被路由守卫拦截
const {
  messages,
  inputMessage,
  loading,
  chatContainerRef,
  currentModel,
  isMobileMenuOpen,
  modelOptions,
  conversations,
  loadingConversations,
  currentConversationId,
  sendMessage,
  clearChat,
  renderMarkdown,
  loadConversation,
  deleteConversation,
  isMobileView,
  loadConversations: loadChatConversations
} = useChat(isAuthenticated, authToken, handleUnauthorized); // 移除 showLoginModalRef

const isSidebarCollapsed = ref(false)

const toggleSidebar = () => {
  isSidebarCollapsed.value = !isSidebarCollapsed.value
}

const closeMobileSidebar = () => {
  if (isMobileView.value) { // 修正：检查 isMobileView.value
    isMobileMenuOpen.value = false
  }
}

const getCurrentConversationTitle = () => {
  if (!currentConversationId.value || !conversations.value?.length) return '新对话'
  const currentConv = conversations.value.find(conv => conv.id === currentConversationId.value)
  return currentConv ? currentConv.title : '新对话'
}

const handleLogout = () => {
  logout();
  // 登出后跳转到首页
  router.push({ name: 'Landing' });
}

// 监听认证状态，如果变为 false（例如 token 过期被动登出），跳转到登录页
watch(isAuthenticated, (newValue) => {
  if (newValue === false) {
    router.push({ name: 'Login', query: { redirect: router.currentRoute.value.fullPath } });
  }
});

onMounted(() => {
  // ChatPage 加载时，总是加载对话（因为路由守卫保证了已认证）
  console.log('ChatPage mounted, loading conversations...');
  loadChatConversations();
});

// 提供给子组件的状态 (如果需要)
provide('authToken', authToken);
provide('user', user);

</script>

<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <aside :class="['sidebar', {
      'collapsed': isSidebarCollapsed,
      'mobile-open': isMobileMenuOpen
    }]">
       <button v-if="!isMobileView" class="toggle-sidebar-btn" @click="toggleSidebar">
        <el-icon :size="14">
          <arrow-right v-if="isSidebarCollapsed" />
          <arrow-left v-else />
        </el-icon>
      </button>

      <div class="sidebar-content" :class="{ 'hidden': isSidebarCollapsed }">
        <div class="sidebar-header">
          <h2>AI 助手</h2>
        </div>

        <button class="new-chat-btn" @click="clearChat">
          <el-icon :size="14">
            <plus />
          </el-icon>
          <span v-if="!isSidebarCollapsed">新对话</span>
        </button>

        <div class="conversations-list" v-if="!isSidebarCollapsed">
          <h3>历史对话</h3>
          <div v-if="loadingConversations" class="loading-spinner">
            加载中...
          </div>
          <template v-else>
            <div v-if="!conversations || conversations.length === 0" class="no-conversations">
              暂无历史对话
            </div>
            <div
              v-for="conv in conversations"
              :key="conv.id"
              :class="['conversation-item', { active: currentConversationId === conv.id }]"
              @click="loadConversation(conv.id); closeMobileSidebar()"
            >
              <div class="conversation-title">{{ conv.title }}</div>
              <div class="conversation-actions">
                <button class="delete-btn" @click.stop="deleteConversation(conv.id)">
                  <el-icon :size="14">
                    <delete />
                  </el-icon>
                </button>
              </div>
            </div>
          </template>
        </div>

        <div class="sidebar-footer" v-if="!isSidebarCollapsed">
          <div class="user-info" v-if="user">
            <el-avatar :size="32" :src="user.avatar_url || undefined">
              {{ user.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <span class="username">{{ user.username }}</span>
          </div>
          <el-button type="danger" plain @click="handleLogout" style="width: 100%; margin-top: 1rem;">
            退出登录
          </el-button>
        </div>
      </div>
    </aside>

    <!-- 侧边栏遮罩层 -->
    <div class="sidebar-backdrop" v-if="isMobileMenuOpen" @click="isMobileMenuOpen = false"></div>

    <!-- 主要内容区 -->
    <div class="main-wrapper">
      <main class="main-content">
        <div class="page-header">
          <div class="header-content">
            <button class="mobile-menu-btn" v-if="isMobileView" @click="isMobileMenuOpen = !isMobileMenuOpen">
              <el-icon :size="20"><Menu /></el-icon>
            </button>
            <h1 class="site-title">{{ getCurrentConversationTitle() }}</h1>
            <div class="header-actions"></div>
          </div>
        </div>

        <!-- 修复：添加固定高度容器，避免内容加载时的页面跳动 -->
        <div class="chat-container-wrapper">
          <div class="chat-container" ref="chatContainerRef">
            <div class="chat-main">
              <!-- 聊天消息渲染 -->
              <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
                <div class="message-wrapper">
                  <template v-if="message.role === 'assistant'">
                    <div class="message-content-with-avatar">
                      <div class="avatar">🤖</div>
                      <div class="content-wrapper">
                        <div v-if="currentModel === 'deepseek-reasoner' && message.reasoning_content"
                             class="reasoning-content">
                          <div class="reasoning-header">
                            <el-icon :size="14">
                              <arrow-left />
                            </el-icon>
                            思考过程
                          </div>
                          <div class="reasoning-body" v-html="renderMarkdown(message.reasoning_content)"></div>
                        </div>
                        <div class="message-content" v-html="renderMarkdown(message.content)"></div>
                      </div>
                    </div>
                  </template>
                  <template v-else>
                    <div class="message-content user-message" v-html="renderMarkdown(message.content)"></div>
                  </template>
                </div>
              </div>
              <!-- 加载动画 -->
              <div v-if="loading" class="message assistant">
                <div class="message-content-with-avatar">
                  <div class="avatar">🤖</div>
                  <div class="message-content loading">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="model-selector-in-input-area">
            <el-select v-model="currentModel" size="small" class="model-select-input">
              <el-option
                v-for="option in modelOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </div>
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="1"
              placeholder="输入消息..."
              :disabled="loading"
              @keyup.enter.exact="sendMessage"
              @keyup.enter.shift.exact="inputMessage += '\n'"
              resize="none"
              autosize
              class="chat-input"
            >
            </el-input>
            <el-button
              type="primary"
              :loading="loading"
              @click="sendMessage"
              class="send-button"
              circle
            >
              <el-icon><Promotion /></el-icon> <!-- 添加发送图标 -->
            </el-button>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

